local __require = require
local selfPath = "onefile"
local entry = "main"
local output = "D:/mini/main"
local packages = {}

local function readFile(path)
	path = string.gsub(path,"%.","/")
	return love.filesystem.read(path..".lua") 
	or love.filesystem.read(path.."/init.lua")
end

local function writeFile(path,str)
    local f = io.open(path..".lua","w")
	io.output(f)
	io.write(str)
	io.close(f)
end

local header = [[
local __require  = require
function require(path)
	if packages[path] then
		package.loaded[path] = packages[path](path)
		packages[path] = nil
		return package.loaded[path]
	end
	return package.loaded[path] or __require(path)
end
]]


local function savePackage()
	local str = "packages = {}\n"
	for path,filestr in pairs(packages) do
		str = str.."packages[\""..path.."\"] = function(...)\n"..filestr.."\nend\n"
	end
	return str
end

local dumpString = function(x) 
    return x:gsub(".", function(d) 
        return "\\" .. d:byte()
    end)
end


local function combine()
	local main = readFile(entry)
    local str = savePackage()..header..string.sub(main,string.find(main,"\n")+1,-1)
    --writeFile(output.."check.lua",str)
	local body = dumpString(str)
    local pac = "return loadstring(\""..body.."\")()"
    pac = "return loadstring(\""..(dumpString(pac)).."\")()"
    writeFile(output,pac)

    writeFile("D:/mini/conf",readFile("conf"))
	print("one file done!")
end


function require(...)
    local path = ...
    if not packages[path] then
	    local str = readFile(path)
	    if str then
		    packages[path] = str
		    print(path.." added")
		else
			print("not include "..path)
		end
	end
    return __require(...)
end

return combine